#include "Panel.h"
#include "../Core/glExt.h"
#include "../Core/Color4.h"
#include "../Core/Vector2.h"
#include "../Core/GlPlatform.h"
#include <algorithm>
#include <functional>

namespace Gui {
	Panel::Panel( const Core::Rect2f& rect )
		: Widget( rect ) {
	}

	bool Panel::onMouseDown( const Core::Point2f& pt ) {
		Core::Point2f adj = Core::Point2f( 0, 0 ) + (pt - this->mClientArea.corner(0));
		for ( auto itr = mChildren.begin(), end = mChildren.end(); itr != end; ++itr ) {
			if ( (*itr)->onMouseDown(adj) ) {
				mActiveObject = *itr;
				return true;
			}
		}
		return false;
	}

	bool Panel::onMouseUp( const Core::Point2f& pt ) {
		Core::Point2f adj = Core::Point2f( 0, 0 ) + (pt - this->mClientArea.corner(0));
		if ( mActiveObject ) {
			mActiveObject->onMouseUp( adj );
			return true;
		}
		return false;
	}

	void Panel::render() {
		using namespace Core;
		glBegin( GL_QUADS ); {
			glExt::emitColor( mColor );
			mClientArea.eachCorner( glExt::emitVertex2<float> );
		} glEnd();
		glPushMatrix(); {
			glTranslatef( mClientArea.left, mClientArea.bottom, 0 );
			std::for_each( mChildren.begin(), mChildren.end(), std::mem_fn( &Widget::render ) );
		} glPopMatrix();
	}
}